import { GlobalConfig } from "../../GlobalConfig";
import { Singleton } from "../class_base/Singleton";
import { Loger } from '../loger/Loger';
import { ResUtils } from '../utils/ResUtils';


/**加载完的策划配置表,都存在这里面 */
export class ConfigMgr extends Singleton {

    /**配置表导出的完整数据 */
    private _cfg: { [key: string]: { [key: string]: any } } = null;
    private _setConfig(cfg: any) {
        this._cfg = cfg;
    }

    /**
     * @desc 根据表名和id取出配置
     * @param cfg_name 表名
     * @param id id
     * @returns 
     */
    public getConfig<T>(cfg_name: string, id: string): T {
        const table = this.getTable(cfg_name);
        if (!table || !table[id]) {
            Loger.error(`找不到配置表${cfg_name},对应的id数据, id:${id}`);
            return null;
        }
        return this._cfg[cfg_name][id] as T;
    }

    /**
     * @desc 根据表名取出整个配置表
     * @param cfg_name 表名
     * @returns 
     */
    public getTable<T>(cfg_name: string): { [key: string]: T } {
        if (!this._cfg[cfg_name]) {
            Loger.error(`找不到配置表: cfg_name : ${cfg_name}`);
            return null;
        }
        return this._cfg[cfg_name] as { [key: string]: T };
    }

    public loadConfig(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            if (GlobalConfig.debug) {
                ResUtils.loadRes(GlobalConfig.localConfig).then(cfg => {
                    this._setConfig(cfg)
                    resolve();
                })
            } else {
                // const url = Boot.onlineConfig;
                // ResUtils.loadOnlineCfg(url).then(cfg => {
                //     this.setConfig(cfg)
                //     resolve(cfg);
                // })
                ResUtils.loadRes(GlobalConfig.localConfig).then(cfg => {
                    this._setConfig(cfg)
                    resolve();
                })
            }
        })
    }

}
